#pragma once
#include "Log.hpp"
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include<iostream>
#include <string>
#include <strings.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>

class Sock
{
public:
    Sock(){}
    int Socket()
    {
        int serversock=socket(AF_INET, SOCK_DGRAM, 0);
        if(serversock < 0)
        {
            logMessage(FATAL, "%d:%s",errno,strerror(errno));
            exit(1);
        }
        return serversock;
    }
    void Bind(int sock,uint16_t port,std::string ip)
    {
        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        socklen_t len=sizeof(server);
        server.sin_family=AF_INET;
        server.sin_port=htons(port);
        server.sin_addr.s_addr=inet_addr(ip.c_str());
        if(bind(sock, (struct sockaddr*)&server, len) < 0)
        {
            logMessage(FATAL, "%d:%s",errno,strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "%d:%s",errno, strerror(errno));
    }
    int Accept(int sock,uint16_t* port,std::string* ip)
    {
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        //这里的sock应该是服务端传过来的sock，只不过是被客户端接受过来的而已
        int clientsock=accept(sock, (struct sockaddr*)&client, &len);
        if(clientsock < 0)
        {
            logMessage(FATAL, "%d:%s",errno,strerror(errno));
            exit(1);
        }
        if(port){
            *port=ntohs(client.sin_port);
        }
        if(ip){
            *ip=inet_ntoa(client.sin_addr);
        }
        return clientsock;
    }
    void Listen(int sock)
    {
        if(listen(sock, gLevelLog) < 0)
        {
            logMessage(FATAL, "%d:%s",errno,strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "%d:%s",errno,strerror(errno));
    }
    void Connet(int sock,uint16_t port,std::string ip)
    {
        struct sockaddr_in server;
        socklen_t len=sizeof(server);
        server.sin_family=AF_INET;
        server.sin_port=htons(port);
        server.sin_addr.s_addr=inet_addr(ip.c_str());
        //在这里接受到了来自于服务端的套接字就可以进行连接了
        int ret=connect(sock, (struct sockaddr*)&server, len);
        if(ret >= 0){
            logMessage(NORMAL, "connet done");
            exit(1);
        }
    }
private:
    static const int gLevelLog=20;
};